﻿using System.Drawing;
using System.Threading;

namespace TwinHead.Frameworks.WindowForms.Effects
{
    /// <summary>
    /// 창 흔드는 효과를 내주는 효과 클래스 입니다.
    /// </summary>
    public sealed class ShakingForm
    {
        /// <summary>
        /// 흔듭니다.
        /// </summary>
        /// <param name="ctxThread">
        /// <para>동기화 컨텍스트</para>
        /// <para>System.Windows.Forms.WindowsFormsSynchronizationContext.Current를 통해 획득할 수 있습니다.</para>
        /// </param>
        /// <param name="targetForm">흔들 폼</param>
        public void Shaking( System.Threading.SynchronizationContext ctxThread, System.Windows.Forms.Form targetForm )
        {
            if (ctxThread == null) return;
            if (targetForm == null) return;

            ThreadPool.QueueUserWorkItem( new WaitCallback( ( object target ) =>
                {
                    Run( ctxThread, targetForm );
                } ) );
        }

        private void Run( System.Threading.SynchronizationContext ctxThread, System.Windows.Forms.Form targetForm )
        {
            Point myLoc = targetForm.Location;
            Point myDefaultLoc = targetForm.Location;

            for (int i = 0; i < 20; i++)
            {
                for (int x = 0; x <= 4; x++)
                {
                    switch (x)
                    {
                        case 0:
                            myLoc.X = myDefaultLoc.X + 10;
                            break;
                        case 1:
                            myLoc.X = myDefaultLoc.X - 10;
                            break;
                        case 2:
                            myLoc.Y = myDefaultLoc.Y + 10;
                            break;
                        case 3:
                            myLoc.Y = myDefaultLoc.Y - 10;
                            break;
                        case 4:
                            myLoc = myDefaultLoc;
                            break;
                    }

                    Thread.Sleep( 10 );

                    ctxThread.Send( new SendOrPostCallback( ( object target ) =>
                    {
                        targetForm.Location = myLoc;
                    } ), null );
                }
            }
        }
    }
}
